﻿#region usings

using System;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using System.Reflection;

#endregion

namespace SimpleDataAccessConsole.DataAccessLayer
{
    public static class Commands
    {
        public static IDbCommand CreateCommand(this IDbCommand command, SimpleQuery simplequery)
        {
            return CreateCommandWithParameters(command, simplequery.CommandText, simplequery.Parameters, simplequery.CommandType);
        }

        public static IDbCommand CreateCommandWithParameters(this IDbCommand command, string sql, object[] args, CommandType commandType = CommandType.Text)
        {
            if (commandType == CommandType.StoredProcedure && command is OdbcCommand)
            {
                //wrap the function name with ODBC crap
                sql = String.Format("{{call {0}({1})}}", sql, String.Join(", ", new string[args.Length].Select(n => "?").ToArray()));
            }

            command.CommandType = commandType;
            command.CommandText = sql;
            command.CommandTimeout = 0;

            if (args != null)
            {
                foreach (var arg in args)
                {
                    var parameter = command.CreateParameter();
                    parameter.ParameterName = Guid.NewGuid().ToString();
                    parameter.Value = arg;

                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }

        //     <system.data>
        //    <DbProviderFactories>
        //       <add name="System.Data.SqlClient"         
        //           invariant="System.Data.SqlClient"         
        //           support="FF" 
        //           description="SqlClient Provider Factory"      
        //           type="System.Data.SqlClient.SqlClientFactory, System.Data, Version=2.0.3600.0, Culture=neutral"/>
        //       <add name="System.Data.OdbcFactory"         
        //           invariant="System.Data.OdbcFactory"         
        //           support="FF" 
        //           description="Odbc Provider Factory"      
        //           type="System.Data.Odbc.OdbcFactory, System.Data, Version=2.0.3600.0, Culture=neutral"/>
        //    </DbProviderFactories>
        //</system.data>
    }
}